//95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个
var cart = {};
//加载本地购买物数据

//#region   主要用出显示本地购物车的数量不用跟服务费进行交互
cart.loadcartlocal = function (clubid) {
  return new Promise((resolve) => {
    var app = getApp();

    if (app.globalData.cart) {

      resolve(cart.loadcartlocal_data(clubid))
    } else {

      wx.getStorage({
        key: 'cart',
        success: function (res) {
          // 将数据从缓存里读出
          try {
            app.globalData.cart = JSON.parse(res.data);


          } catch (ex) {
            app.globalData.cart = {};
          }

          resolve(cart.loadcartlocal_data(clubid))
        },
        fail: function (e) {
          app.globalData.cart = {};
          resolve(cart.loadcartlocal_data(clubid))
        },
        complete: function (d) {

        }
      })
    }
  })
}

cart.loadcartlocal_data = function (clubid) {
  var app = getApp();
  var cartdata = app.globalData.cart

  for (var i in cartdata) {

    if (cartdata[i].protype == 2 && clubid != cartdata[i].clubid) {

      delete cartdata[i]
    }
  }

  return {
    cart: cartdata,
    totalnuminfo: cart.totalnuminfo(cartdata),
    groupcarnum: cart.groupbyactype(cartdata)
  }
}

cart.groupbyactype = function (htcart) {
    var groupht = {
      pro: {},
      prolimit: {}
    }

    var temlimitpro = null;
    for (var a in htcart) {
      var temattr = a.split("_");
      switch (temattr[1]) {
        case "0": {
          if (!groupht["pro"][temattr[0]]) {
            groupht["pro"][temattr[0]] = htcart[a]["num"]
          } else {
            groupht["pro"][temattr[0]] += htcart[a]["num"]
          }
          break;
        }
        case "1": {
          if (!groupht["prolimit"][temattr[2]]) {
            groupht["prolimit"][temattr[2]] = {};
          }
          temlimitpro = groupht["prolimit"][temattr[2]];
          if (!temlimitpro[temattr[0]]) {
            temlimitpro[temattr[0]] = htcart[a]["num"]
          } else {
            temlimitpro[temattr[0]] += htcart[a]["num"]
          }
          break;
        }
      }
    }






    return groupht;

  },

  cart.totalnuminfo = function (cart) {
    var totalnum = 0
    var selectednum = 0;
    var sumprice = 0
    if (cart) {
      for (var a in cart) {

        totalnum += parseInt(cart[a]["num"]);
        if (cart[a].ischecked) {


          selectednum += parseInt(cart[a]["num"]);

          if (cart[a].cid) {
            cart[a].cid = cart[a].cid + "";
          } else {
            cart[a].cid = "0";
          }

          switch (cart[a].cid) {
            case "0": {
              sumprice = sumprice + cart[a].realprice * cart[a].num;
              break;
            }
            case "1": {
              sumprice = sumprice + cart[a].activityprice * cart[a].num;
              break;
            }
          }
          // var key=
          // if(a.indexOf("_1_")>0 ){
          //   sumprice+=cart[a]["num"]*cart[a].activityprice
          //   console.log("sumprice1111111")

          //   console.log(sumprice)
          // }
          // else
          // {

          //   console.log("sumprice222")

          //   sumprice+=cart[a]["num"]*cart[a].realprice
          //   console.log(sumprice)

          // }

        }
      }
    }

    return {
      totalnum,
      selectednum,
      sumprice
    };
  }
//#endregion

cart.loadcart = function () {
  var app = getApp();

  wx.getStorage({
    key: 'cart',
    success: function (res) {
      // 将数据从缓存里读出
      try {
        app.globalData.cart = JSON.parse(res.data);


      } catch (ex) {
        app.globalData.cart = {};
      }

      // return cart.loadcartPromise();
    },
    fail: function (e) {
      app.globalData.cart = {};

    },
    complete: function (d) {}
  })


}


cart.cleardada = function () {
    var app = getApp()

    return new Promise(function (resolve) {
      if (app.globalData.cart) {

        app.globalData.cart = {}

        wx.setStorage({
          key: "cart",
          data: JSON.stringify(app.globalData.cart),
          success: function (et) {
            resolve({
              status: 1
            })
          }

        })

      }

    })

  },

  cart.getnum = function () {

    return new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'cart',
        success: function (res) {

          if (res.data) {

          }
        }

      })
    })
    var app = getApp();
    if (app.globalData.cart) {

    }

  }





/**
 * promodel 加入的产品
 * cid 0普通订单
 * activityid =活动id
 */
cart.cartaddold = function (promodel, cid, activityid) {


  if (!promodel.protype) {
    promodel.protype = 1
  }
  promodel["ischecked"] = true

  var app = getApp();
  if (app.globalData.cart == null) {
    app.globalData.cart = {};
  }
  if (!cid) {
    cid = 0;
  }
  if (!activityid) {
    activityid = 0;
  }
  var arrkeyvals = [];
  arrkeyvals.push(promodel.id);
  arrkeyvals.push(cid);
  arrkeyvals.push(activityid);

  //  //95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个 protype产品类型1商城产品2团长产品
  if (promodel.attrs && promodel.attrs.length > 0) {
    var attrs = [];
    for (var a in promodel.attrs) {
      attrs.push(promodel.attrs[a].keyval);
    }
    arrkeyvals.push(attrs.join("x"));
  } else {

    arrkeyvals.push("-1");
  }
  arrkeyvals.push(promodel.protype);
  var keyval = arrkeyvals.join("_");

  if (app.globalData.cart[keyval]) {
    app.globalData.cart[keyval]["num"] += parseInt(promodel["num"]);
  } else {
    app.globalData.cart[keyval] = promodel;
  }

  if (!app.globalData.cart[keyval]["ischecked"]) {
    app.globalData.cart[keyval]["ischecked"] = true
  }


 

  // cid=0 普通订单
  // promodel["keyval"] // "id_cid_activityid_attrs.join"   
  wx.setStorage({
    key: "cart",
    data: JSON.stringify(app.globalData.cart),
    success: function (et) {}
  })
}

//
cart.querycartadd = function (item) {
    var app = getApp();
    if (app.globalData.purchaseorder == null) {
      app.globalData.purchaseorder = {};
    }
    var id = item['id']
    if (!app.globalData.purchaseorder[id]) {
      app.globalData.purchaseorder[id] = {}
    }
    var attrs = {};
    for (var i in item['attrs']) {
     
      attrs[item['attrs'][i]["key"]] = {
        num: item['attrs'][i]["num"],
        ischecked: true
      }
    }

    app.globalData.purchaseorder[id] = attrs


    wx.setStorage({
      key: "purchaseorder",
      data: JSON.stringify(app.globalData.purchaseorder),
      success: function (et) {}
    })
  },
  //订单重复购买
  cart.buyagain = function (orderinfo) {
    orderinfo.forEach(function (item) {

      cart.querycartadd(item)
    })
  }
/**
 * selected 加入的产品
 */
cart.cartadd = function (selected) {

  var app = getApp();
  if (app.globalData.purchaseorder == null) {

    this.loadpurchaseorder().then(res=>{
        this.cartaddpro(selected)
    })
  }else{
    this.cartaddpro(selected)
  }

}

cart.cartaddpro =  function (selected) {

  var app = getApp();
  var keyval = selected.proid

  var newattrs = {};
  for (var i in selected.attrs) {
    if (selected.attrs[i]['num'] > 0) {
      newattrs[i] = {}
      if (app.globalData.purchaseorder[keyval] && app.globalData.purchaseorder[keyval][i + '']) {
        newattrs[i]['num'] = app.globalData.purchaseorder[keyval][i + '']['num'] + selected.attrs[i]['num'] //选择的数量

      } else {
        newattrs[i]['num'] = selected.attrs[i]['num'] //选择的数量
      }

      newattrs[i]['ischecked'] = true; //选中状态
    }
  }

  app.globalData.purchaseorder[keyval] = newattrs



  wx.setStorage({
    key: "purchaseorder",
    data: JSON.stringify(app.globalData.purchaseorder),
    success: function (et) {}
  })
}
/**
 * 加载purchaseorder数据
 */
 cart.loadpurchaseorder = function () {
  var app = getApp();
  if (app.globalData.purchaseorder) {

    return app.globalData.purchaseorder;
  } else {

    return new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'purchaseorder',
        success: function (res) {
         
          // 将数据从缓存里读出
          try {
            app.globalData.purchaseorder = JSON.parse(res.data);
            resolve(JSON.parse(res.data));
          } catch (ex) {
            reject({
              code: "faill",
              message: ex
            });
            app.globalData.purchaseorder = {};
          }
        },
        fail: function (e) {
          
          resolve({});
          app.globalData.purchaseorder = {};
        }
      })
    })
  }
}
/**
 * 加载进货单数据
 */
cart.loadcartPromise = function () {
  var app = getApp();
  if (app.globalData.purchaseorder) {
    return cart.loadservedata();
  } else {
    return new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'purchaseorder',
        success: function (res) {
          // 将数据从缓存里读出
          try {
            app.globalData.purchaseorder = JSON.parse(res.data);
            cart.loadservedata().then(function (eda) {
              resolve(eda);
            }, function (edb) {
              reject(edb)
            })
          } catch (ex) {
            reject({
              code: "faill",
              message: ex
            });
            app.globalData.purchaseorder = {};
          }
        },
        fail: function (e) {
          // reject({ code: "faill", message: e });
          resolve({
            code: "success",
            data: []
          });
          app.globalData.purchaseorder = {};
        }
      })
    })
  }
}
/**
 * 数据库中获取产品的信息
 */
cart.loadservedata = function () {
  return new Promise(function (resolve, reject) {
    var app = getApp();
    var postdata = {};
    var keyvalues = Object.keys(app.globalData.purchaseorder);

    if (keyvalues.length < 1) {
      resolve({
        code: "success",
        data: []
      })
    }
    postdata["op"] = "getcartinfo";
    postdata["keyvalues"] = keyvalues.join(",");
    postdata['plugin'] = "wholesale"
    app.util.request({
      'url': 'entry/wxapp/wholesalepro_cart',
      showLoading: false,
      'data': postdata,
      success: function (res) {
        if (res.data.errno == 0 && res.data.data["status"] == 1) {
          // console.log("res.data.data")
          // console.log(res.data.data)
          // if (res.data.data["obj"]["guigetype"] != "-1") {
          //   res.data.data["obj"]["skuht"] = sku(res.data.data["obj"]["skudata"]);
          // }
          // var invalidkeys=res.data.data["invalidkeys"];
          // if(invalidkeys){
          //   for(var i in invalidkeys){
          //     cart.setnum(invalidkeys[i], 0)
          //   }
          // } 

          var data = res.data.data["obj"];
          if (data && data.length > 0) {
            for (var a in data) {

              if (data[a]['guigetype'] == 1) { //有规格的情况
                data[a]["skuht"] = sku(data[a]["skudata"], data[a]['agent']);
                data[a]['attrs'] = attrs(data[a]['skuht'], app.globalData.purchaseorder[data[a]["id"]])
              } else {
                var item = {
                  stock: data[a]['stock'],
                  realprice: data[a]['realprice'],
                  price: data[a]['price'],
                  num: app.globalData.purchaseorder[data[a]["id"]][-1]['num'],
                  ischecked: app.globalData.purchaseorder[data[a]["id"]][-1]['ischecked'],
                };
                var agent = data[a]['agent'];
                item = singleagent(item, agent)

                data[a]['attrs'] = {
                  '-1': item
                }

              }

            }
            resolve({
              code: "success",
              exinfo: res.data.data["exinfo"],
              data: data,
              nowtime: res.data.data["nowtime"]
            })
          } else {
            resolve({
              code: "warn",
              data: data,
              nowtime: res.data.data["nowtime"]
            })
          }
        } else {
          reject({
            code: "fail"
          });
        }
      },
      fail: function (res) {
        reject(((res.data && res.data.message) ? res.data.message : res.errMsg));
      },

    })
  })
}
/**
 * 更新数量
 */
cart.setnum = function (id, key, num) {
  var app = getApp();

  if (app.globalData.purchaseorder[id] && app.globalData.purchaseorder[id][key]) {
    if (num == 0) {

      delete app.globalData.purchaseorder[id][key]
      if (Object.keys(app.globalData.purchaseorder[id]).length == 0) {
        delete app.globalData.purchaseorder[id]
      }

    } else if (num >= 1) {
      app.globalData.purchaseorder[id][key]["num"] = num;
      if (!app.globalData.purchaseorder[id][key]["ischecked"]) {
        app.globalData.purchaseorder[id][key]["ischecked"] = true;
      }

    }
  } else {
    wx.showToast({
      icon: "error",
      title: '出错了！',
    })
  }


  wx.setStorage({
    key: "purchaseorder",
    data: JSON.stringify(app.globalData.purchaseorder),
    success: function (et) {}
  })

}
/**
 * 删除选中
 */
cart.removeselected = function () {
  var app = getApp()
  if (app.globalData.purchaseorder) {

    for (var a in app.globalData.purchaseorder) {
      for (var b in app.globalData.purchaseorder[a]) {
        if (app.globalData.purchaseorder[a][b].ischecked) {
          delete app.globalData.purchaseorder[a][b]
        }
      }
      if (Object.keys(app.globalData.purchaseorder[a]).length == 0) {
        delete app.globalData.purchaseorder[a]
      }
    }

    wx.setStorage({
      key: "purchaseorder",
      data: JSON.stringify(app.globalData.purchaseorder),
      success: function (et) {}
    })

  }
}
/**
 * 设定选中状态
 * @param {*} keyval 
 * @param {*} chkval 
 */
cart.setchk = function (id, key, chkval) {
  var app = getApp();

  app.globalData.purchaseorder[id][key]["ischecked"] = chkval;
  wx.setStorage({
    key: "purchaseorder",
    data: JSON.stringify(app.globalData.purchaseorder),
    success: function (et) {}
  })
}

function singleagent(item, agent) {
  var app = getApp();


  var wsgrade = app.globalData.member.memberinfo.wsgrade;

  if (agent['status'] == 1) {
    if (agent['calc'] == 'fixed') {
      item["wsprice"] = agent['data'][0][wsgrade];
    } else {

      item["wsprice"] = item["realprice"] * agent['data'][0][wsgrade] * 0.0001;

    }
  } else {
    var agent = app.globalData.configdata.wholesale.agent;
    var discount = agent.grade[wsgrade].discount
    item["wsprice"] = item["realprice"] * discount * 0.01
  }

  return item;
}

function attrs(skuht, selected) {
  var attrs = {};
  var index = 0;
  for (var i in skuht) {
    if (selected[i] && selected[i]['num'] > 0) {
      skuht[i]['num'] = selected[i]['num']
      skuht[i]['ischecked'] = selected[i]['ischecked']
      skuht[i]['key'] = i.split("_")
      skuht[i]['index'] = index

      attrs[i] = skuht[i]
    }
    index++
  }
  return attrs
}

function wsprice(i, realprice, wsgrade, agent) {

  if (agent['status'] == 1) {
    if (agent['calc'] == 'fixed') {

      return agent['data'][i][wsgrade];

    } else {
      var prices = realprice * agent['data'][i][wsgrade] * 0.0001

      return prices.toFixed(0);

    }

  } else {
    var app = getApp();

    var sysagent = app.globalData.configdata.wholesale.agent;
    var discount = sysagent.grade[wsgrade].discount
    var price = realprice * discount * 0.01
    return price.toFixed(0);

  }

}

function sku(sku, agent) {
  var app = getApp();

  var wsgrade = app.globalData.member.memberinfo.wsgrade;

  var arrs = [];
  for (var i = 0; i < sku.grouplabel.length; i++) {
    var attr = [];
    for (var n = 0; n < sku.grouplabel[i]["attrs"].length; n++) {
      attr.push(n);
    }
    arrs.push(attr);
  }
  //array.fill(value, start, end)
  var cartesianproduct = Array.prototype.reduce.call(arrs, function (a, b) {
    var ret = [];
    a.forEach(function (a) {
      b.forEach(function (b) {
        ret.push(a.concat([b]));
      });
    });
    return ret;
  }, [
    []
  ]);
  var skuht = {};
  sku.stockdata.forEach(function (val, i) {
    skuht[cartesianproduct[i].join("_")] = {
      stock: parseInt(val["stock"]),
      isshow: val["isshow"],
      weight: val["weight"],
      isdefault: val["isdefault"],
      salesvolume: val["salesvolume"],
      simg: val["simg"],
      fullsimg: val["fullsimg"],
      price: val["price"],
      realprice: val["realprice"],
      activityprice: 0,
      wsprice: wsprice(i, val["realprice"], wsgrade, agent)
    }
  })
  return skuht;
}
module.exports = cart